package com.allwees.bs.c.module.order.context.compute.strategy.marketing;


import com.allwees.bs.c.module.order.context.bo.CouponComputeBo;
import com.allwees.bs.c.module.product.service.FreeGiftRecordService;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

@Service
public class FreeGiftMarketingStrategy implements MarketingStrategy {

    @Autowired
    private FreeGiftRecordService freeGiftProductService;


    @Override
    public CouponComputeBo strategy(CouponComputeBo computeBo) {
        AtomicInteger freeGiftCount = new AtomicInteger();
        computeBo.getItems().forEach(couponComputeItemBo -> {
            if (couponComputeItemBo.isFreeGift()) {
                freeGiftCount.addAndGet(couponComputeItemBo.getQuantity());
                if (freeGiftCount.get() > 1) {
                    throw BusinessException.getInstance(ResultEnum.ORDER_MORE_THAN_ONE_FREEGIFT);
                }

                if(freeGiftProductService.hasApplied(computeBo.getUserUuid())){
                    throw BusinessException.getInstance(ResultEnum.ORDER_MORE_THAN_ONE_FREEGIFT);
                }

            }
        });

        return computeBo;
    }
}
